package io;

import java.io.*;
import java.util.Properties;

/**
 * io流练习
 */
public class IoExercise03 {

    public static void main(String[] args) {

        /*
            编写一个dog.properties
            name=tom
            age=5
            color=red
            编写类Dogs(name age color)创建一个dog对象，读取dog.properties用相应的内容完成初始化，并输出
            将创建的dog对象，序列化到文件dog.dat文件
         */
        String propertiesPath = "src\\dog.properties";
        String serializablePath = "D:\\IdeaCode\\javaStudy\\dog.dat";
        Dogs dogs = new Dogs();

        Properties properties = new Properties();
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try {
            //1.读取属性
            properties.load(new FileInputStream(propertiesPath));
            String name = properties.getProperty("name");
            String age = properties.getProperty("age");
            String color = properties.getProperty("color");
            dogs.setAge(Integer.parseInt(age));
            dogs.setName(name);
            dogs.setColor(color);
            System.out.println("dog对象信息：" + dogs);

            //2.序列化
            oos = new ObjectOutputStream(new FileOutputStream(serializablePath));
            oos.writeObject(dogs);
            System.out.println("序列化成功...");

            //3.反序列化测试
            ois = new ObjectInputStream(new FileInputStream(serializablePath));
            Object o = ois.readObject();
            if (o instanceof Dogs) {
                System.out.println("====反序列化后输出====");
                Dogs d =  (Dogs) o;
                System.out.println(d);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}

class Dogs implements Serializable {

    private String name;

    private int age;

    private String color;

    public Dogs() {
    }

    public Dogs(String name, int age, String color) {
        this.name = name;
        this.age = age;
        this.color = color;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    @Override
    public String toString() {
        return "Dogs{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", color='" + color + '\'' +
                '}';
    }
}